// @algorithm @lc id=100279 lang=cpp
// @title ju-zhen-zhong-de-lu-jing-lcof

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
    vector<int> direction{-1, 0, 1, 0, -1};
    bool exist(vector<vector<char>> &board, string word) {
        if (board.empty()) {
            return false;
        }
        int m = board.size();
        int n = board[0].size();
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        bool find = false;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                backtracking(i, j, board, word, find, visited, 0);
            }
        }
        return find;
    }

    void backtracking(int i, int j, vector<vector<char>> &board, string &word, bool &find, vector<vector<bool>> &visited, int pos) {
        if (i < 0 || i >= (int)board.size() || j < 0 || j >= (int)board[0].size()) {
            return;
        }
        if (visited[i][j] || find || board[i][j] != word[pos]) {
            return;
        }
        if (pos == (int)word.size() - 1) {
            find = true;
            return;
        }
        visited[i][j] = true;
        for (int z = 0; z < 4; ++z) {
            int x = i + direction[z];
            int y = j + direction[z + 1];
            backtracking(x, y, board, word, find, visited, pos + 1);
        }
        visited[i][j] = false;
    }
};